package com.cater.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cater.annotation.SystemControllerLog;
import com.cater.common.PageResult;
import com.cater.project.entity.DemandCommunicate;
import com.cater.project.entity.DemandEnterprise;
import com.cater.project.entity.TbContract;
import com.cater.project.service.DemandCommunicateServiceImpl;
import com.cater.project.service.DemandEnterpriseServiceImpl;
import com.cater.project.service.TbContractServiceImpl;
import com.cater.query.CommonQuery;
import com.cater.sys.entity.Company;
import com.cater.sys.entity.Industry;
import com.cater.sys.service.impl.CompanyServiceImpl;
import com.cater.sys.service.impl.ContactServiceImpl;
import com.cater.sys.service.impl.IndustryServiceImpl;
import com.cater.talents.entity.Contact;
import com.cater.talents.entity.Resume;
import com.cater.talents.entity.TalentsRecommend;
import com.cater.talents.service.ResumeServiceImpl;
import com.cater.talents.service.TalentsRecommendServiceImpl;

/**
 * @author yong
 * @Date 2018年3月23日-上午10:57:20
 * @公司管理控制层
 */
@Controller
@RequestMapping("/company")
public class CompanyController {

	@Autowired
	private CompanyServiceImpl service;
	@Autowired
	private IndustryServiceImpl industryService;
	@Autowired
	private DemandEnterpriseServiceImpl enterpriseService;
	@Autowired
	private TalentsRecommendServiceImpl recommendService;
	@Autowired
	private ResumeServiceImpl resumeService;
	@Autowired
	private ContactServiceImpl contactService;
	@Autowired
	private TbContractServiceImpl contractService;
	@Autowired
	private DemandCommunicateServiceImpl communicateService;
	@Autowired
	private DemandEnterpriseServiceImpl demandEnterpriseService;

	/**
	 * @公司管理列表视图
	 * @return
	 */
	@RequestMapping("/list")
	public String list() {
		return "company/manage/list";
	}

	/**
	 * @公司管理数据分页
	 * @param query
	 * @param request
	 * @return
	 */
	@RequestMapping("listData")
	@ResponseBody
	@SystemControllerLog(description = "查询公司分页数据")
	public PageResult<Company> listData(CommonQuery query, HttpServletRequest request) {
		PageResult<Company> result = service.findPageResult(query);
		return result;
	}

	/**
	 * 添加视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addView")
	@RequiresPermissions("company:add")
	public String addView(Model model) {
		List<Industry> industries = industryService.getAll();
		model.addAttribute("industry", industries);
		return "company/manage/add";
	}

	/**
	 * 添加操作
	 * 
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "add")
	@RequiresPermissions("company:add")
	@ResponseBody
	@SystemControllerLog(description = "添加公司")
	public JSONObject add(Company t, CommonQuery query) {
		JSONObject json = new JSONObject();
		query.setName(t.getName());
		Company company = service.getByName(query);
		if (company != null) {
			json.put("code", 999);
			json.put("message", "公司名称已存在");
		} else {
			String id = service.saves(t);
			if (StringUtils.isNotBlank(id)) {
				json.put("code", 200);
				json.put("message", "success");
			} else {
				json.put("code", 999);
				json.put("message", "fail");
			}
		}
		return json;
	}

	/**
	 * 修改视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "editView")
	@RequiresPermissions("company:edit")
	public String editView(String id, Model model, CommonQuery query) {
		Company t = service.getById(id);
		model.addAttribute("company", t);
		List<Industry> industries = industryService.getAll();
		model.addAttribute("industry", industries);
		return "company/manage/update";
	}

	/**
	 * 修改操作
	 * 
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "update")
	@RequiresPermissions("company:edit")
	@ResponseBody
	@SystemControllerLog(description = "修改公司")
	public JSONObject update(Company t, CommonQuery query) {
		JSONObject json = new JSONObject();
		try {
			Company company = service.getById(t.getId());
			int count = 0;
			if (!t.getName().equals(company.getName())) {
				query.setName(t.getName());
				Company companyc = service.getByName(query);
				if (companyc != null) {
					count = 1;
				}
			}
			if (count > 0) {
				json.put("code", 999);
				json.put("message", "公司名称已存在");
			} else {
				service.update(t);
				json.put("code", 200);
				json.put("message", "修改成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "修改失败");
		}
		return json;
	}

	/**
	 * 删除操作
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("company:delete")
	@SystemControllerLog(description = "删除公司")
	public JSONObject delete(String id) {
		JSONObject json = new JSONObject();
		try {
			service.delete(id);
			json.put("code", 200);
			json.put("message", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "删除失败");
		}
		return json;
	}

	/**
	 * 查看视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "detailView")
	@RequiresPermissions("company:detail")
	public String detailView(String id, Model model, CommonQuery query) {
		Company t = service.getById(id);
		model.addAttribute("company", t);
		List<DemandEnterprise> demandEnterprises = enterpriseService.getByCompanyId(id);
		if (!demandEnterprises.isEmpty() && demandEnterprises.size() > 0) {
			for (DemandEnterprise demandEnterprise : demandEnterprises) {
				Contact contact = contactService.getContactBy(demandEnterprise.getCompanyId(),
						demandEnterprise.getContact());
				if (contact != null) {
					demandEnterprise.setContacts(contact);
				}
			}
		}
		model.addAttribute("demands", demandEnterprises);
		model.addAttribute("demands_count", demandEnterprises.size());
		List<TalentsRecommend> recommends = recommendService.getByCompanyId(id);
		model.addAttribute("recommends", recommends);
		model.addAttribute("recommends_count", recommends.size());
		query.setCompanyId(id);
		List<TbContract> contracts = contractService.getListBy(query);
		model.addAttribute("contracts", contracts);
		model.addAttribute("contracts_count", contracts.size());
		query.setCompanyId(id);
		List<DemandCommunicate> communicates = communicateService.getListBy(query);
		model.addAttribute("communicates", communicates);
		model.addAttribute("communicates_count", communicates.size());
		return "company/manage/detail";
	}

	/**
	 * @获取单条数据
	 * @param query
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getById")
	public JSONObject getById(String id) {
		JSONObject json = new JSONObject();
		try {
			Company company = service.getById(id);
			json.put("company", company);
			json.put("code", 200);
			json.put("message", "数据获取成功");
		} catch (Exception e) {
			json.put("company", "");
			json.put("code", 200);
			json.put("message", "数据获取失败");
		}
		return json;
	}

	@ResponseBody
	@RequestMapping("/getJson")
	public List<Company> getJson(CommonQuery query) {
		List<Company> list = service.getAllCommon(query);
		return list;
	}

	@ResponseBody
	@RequestMapping("/getJsonCompany")
	public List<Map<String, Object>> getJsonCompany(CommonQuery query) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		String names = query.getName().replace("'", "");
		query.setName(names);
		List<Company> companies = this.service.getAllCommon(query);
		for (Company tCompany : companies) {
			map = new HashMap<String, Object>();
			map.put("id", tCompany.getId());
			map.put("value", tCompany.getName());
			map.put("profile", tCompany.getProfile());
			list.add(map);
		}
		return list;
	}

	/**
	 * @已完善的数据提供给企业需求选择
	 * @param query
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getByStatusJson")
	public List<Company> getAllJson(CommonQuery query) {
		List<Company> list = service.getAllByStatus(query);
		return list;
	}

	@RequestMapping("/chooseCompnay")
	public String ChooseCompnay(String companyName, Model model, HttpServletRequest request) {
		if (StringUtils.isEmpty(companyName)) {
			companyName = "";
		}
		model.addAttribute("companyName", companyName);
		String tops = request.getParameter("tops");
		if (StringUtils.isNotBlank(tops)) {
			model.addAttribute("tops", tops);
		}
		return "company/manage/choose_company";
	}

	@ResponseBody
	@RequestMapping("/getByName")
	public JSONObject getByName(CommonQuery query, Model model) {
		JSONObject json = new JSONObject();
		try {
			if (StringUtils.isNotEmpty(query.getName())) {
				Company company = service.getByName(query);
				if (company != null) {
					String profile = company.getProfile();
					if (StringUtils.isNotEmpty(profile)) {
						json.put("profile", profile);
						json.put("code", 200);
						json.put("message", "数据获取成功");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 400);
			json.put("message", "数据获取失败");
		}
		return json;
	}

	@RequestMapping("/contactList")
	public String contactList(String companyId, Model model) {
		model.addAttribute("companyId", companyId);
		return "company/contact/list";
	}

	/**
	 * @公司管理数据分页
	 * @param query
	 * @param request
	 * @return
	 */
	@RequestMapping("contactListData")
	@ResponseBody
	@SystemControllerLog(description = "查询公司分页数据")
	public PageResult<Contact> contactListData(CommonQuery query, HttpServletRequest request) {
		PageResult<Contact> result = contactService.findPageResult(query);
		return result;
	}

	/**
	 * 添加企业联系人
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addContactView")
	@RequiresPermissions("company:addcontact")
	public String addContactView(String companyId, String demandId, CommonQuery query, Model model) {
		if (StringUtils.isNotEmpty(demandId)) {
			DemandEnterprise demandEnterprise = demandEnterpriseService.getById(demandId);
			if (demandEnterprise != null) {
				companyId = demandEnterprise.getCompanyId();
			}
		}
		model.addAttribute("companyId", companyId);
		return "company/manage/add_contact";
	}

	@RequestMapping(value = "addContact")
	@RequiresPermissions("company:addcontact")
	@ResponseBody
	@SystemControllerLog(description = "添加公司对接人")
	public JSONObject addContact(Resume t, Contact contact) {
		JSONObject json = new JSONObject();
		String id = t.getId();
		try {
			if (StringUtils.isNotEmpty(id)) {
				contact.setStatus("1");
				contact.setContactId(id);
				Resume resume = resumeService.getById(id);
				resume.setTrueName(t.getTrueName());
				resume.setCellphone(t.getCellphone());
				resume.setEmail(t.getEmail());
				resume.setWechat(t.getWechat());
				resume.setQq(t.getQq());
				resumeService.update(resume);
			} else {
				String resumeId = resumeService.saves(t);
				if (StringUtils.isNotEmpty(resumeId)) {
					contact.setContactId(resumeId);
				}
			}
			List<Contact> contacts = contactService.getContactList(contact.getCompanyId(), id);
			if (contacts.size() > 0) {
				json.put("code", 400);
				json.put("message", "企业联系人已存在");
			} else {
				contactService.saves(contact);
				json.put("code", 200);
				json.put("message", "企业联系人添加成功");
			}

		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 500);
			json.put("message", "企业联系人添加失败");
		}
		return json;
	}

	@RequestMapping(value = "editContactView")
	@RequiresPermissions("company:editcontact")
	public String editContactView(Contact t, CommonQuery query, Model model) {
		String id = t.getContactId();
		Contact contact = contactService.getContactBy(t.getCompanyId(), id);
		model.addAttribute("contact", contact);
		return "company/contact/edit_contact";
	}

	@RequestMapping(value = "editContact")
	@RequiresPermissions("company:editcontact")
	@ResponseBody
	@SystemControllerLog(description = "修改公司对接人")
	public JSONObject editContact(Resume t, Contact contact) {
		JSONObject json = new JSONObject();
		String id = contact.getContactId();
		try {
			if (StringUtils.isNotEmpty(id)) {
				Resume resume = resumeService.getById(id);
				if (resume != null) {
					resume.setTrueName(t.getTrueName());
					resume.setCellphone(t.getCellphone());
					resume.setEmail(t.getEmail());
					resume.setWechat(t.getWechat());
					resume.setQq(t.getQq());
					resumeService.update(resume);
				}
				Contact contact2 = contactService.getContactBy(contact.getCompanyId(), id);
				if (contact2 != null) {
					contact2.setPosition(contact.getPosition());
					contact2.setStatus(contact.getStatus());
					contactService.update(contact2);
				}
			}
			json.put("code", 200);
			json.put("message", "企业联系人修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 500);
			json.put("message", "企业联系人修改失败");
		}
		return json;
	}

	@ResponseBody
	@RequestMapping("/deleteContact")
	@RequiresPermissions("company:deletecontact")
	@SystemControllerLog(description = "删除公司联系人")
	public JSONObject contactDelete(String companyId, String contactId) {
		JSONObject json = new JSONObject();
		try {
			contactService.deleteUR(companyId, contactId);
			json.put("code", 200);
			json.put("message", "删除公司联系人成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "删除公司联系人失败");
		}
		return json;
	}

	/**
	 * 获取公司联系人
	 * 
	 * @param companyId
	 * @param contactId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getContactBy")
	public JSONObject getContactBy(String companyId, String contactId, String demandId) {
		JSONObject json = new JSONObject();
		try {
			if (StringUtils.isNotEmpty(demandId)) {
				DemandEnterprise demandEnterprise = demandEnterpriseService.getById(demandId);
				if (demandEnterprise != null) {
					companyId = demandEnterprise.getCompanyId();
				}
			}
			List<Contact> list = contactService.getContactList(companyId, contactId);
			if (!list.isEmpty() && list.size() > 0) {
				json.put("contacts", list);
				json.put("code", 200);
				json.put("message", "获取公司联系人成功");
			} else {
				json.put("code", 400);
				json.put("message", "该公司无联系人请添加");
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "获取公司联系人失败");
		}
		return json;
	}

	@ResponseBody
	@RequestMapping("/getcontactById")
	public JSONObject getcontactById(String companyId, String contactId) {
		JSONObject json = new JSONObject();
		try {
			Contact contact = contactService.getContactBy(companyId, contactId);
			if (contact != null) {
				json.put("code", 200);
				json.put("contact", contact);
				json.put("message", "数据获取成功");
			} else {
				json.put("code", 400);
				json.put("message", "暂无数据");
			}
		} catch (Exception e) {
			json.put("code", 500);
			json.put("message", "查询数据异常");
		}
		return json;
	}
}
